(function(window, document) {

    if (window.initGeetest) {
        return;
    }
    var head = document.getElementsByTagName("head")[0];
    var protocol = location.protocol + "//";
    var callbacks = [];
    var status = "init";
    var random = function() {
        return parseInt(Math.random() * 10000) + (new Date()).valueOf();
    };
    var run = function() {
        for (var i = 0, len = callbacks.length; i < len; i = i + 1) {
            callbacks[i]();
        }
        callbacks = [];
    };
    var detect = function() {
        return window.Geetest || document.getElementById("gt_lib");
    };
    var down = function(config) {
        var s = document.createElement("script");
        s.charset = "UTF-8";
        s.type = "text/javascript";
        s.onload = s.onreadystatechange = function() {
            if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                if (detect()) {
                    status = "loaded";
                    run();
                } else {
                    status = "fail";
                    throw new Error("网络错误");
                }
                s.onload = s.onreadystatechange = null;
            }
        };
        s.onerror = function() {
            status = "fail";
            s.onerror = null;
            throw new Error("网络错误");
        };
        var staticServer = (config.staticservers && config.staticservers[0]) || "static.geetest.com/";
        s.src = protocol + staticServer + "static/js/geetest.0.0.0.js";
        head.appendChild(s);
    };

    var getLib = function(config) {
        status = "loading";
        var cb = "geetest_" + random();
        window[cb] = function() {
            status = "loaded";
            run();
            window[cb] = undefined;
            try {
                delete window[cb];
            } catch (e) {}
        };
        var s = document.createElement("script");
        s.charset = "UTF-8";
        s.type = "text/javascript";
        s.onload = s.onreadystatechange = function() {
            if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                if (!detect()) {
                    down(config);
                }
            }
        };
        s.onerror = function() {
            down(config);
        };
        var apiServer = config.apiserver || "api.geetest.com/";
        s.src = protocol + apiServer + "getfrontlib.php?gt=" + config.gt + "&callback=" + cb;
        head.appendChild(s);
    };

    if (detect()) {
        status = "loaded";
    }

    window.initGeetest = function(config, callback) {
        if (typeof config.gt !== "string") {
            throw new Error("")
        }
        var init = function() {
            callback(new window.Geetest(config));
        };
        if (status === "loaded") {
            init();
        } else if (status === "fail") {
            throw new Error("网络错误");
        } else if (status === "loading") {
            callbacks.push(function() {
                init();
            });
        } else if (status === "init") {
            callbacks.push(function() {
                init();
            });
            getLib(config);
        }
    };

})(window, document);

function GT(trigger) {
    this.captchaObj = null;
    this.testStatus = false;
    this.trigger = trigger;
    this.btnText = $(this.trigger).text();
    this.onSuccess = null;
    this.onFail = null;

    this.handlerEmbed = function() {
        var self = this;

        return function(captchaObj) {
            self.captchaObj = captchaObj;

            self.captchaObj.appendTo("#embed-captcha");
            self.captchaObj.bindOn("input#gee-trigger");
            self.captchaObj.onSuccess(function() {
                self.testStatus = true;
                if(self.onSuccess){
                    self.onSuccess();
                }
            });
            self.captchaObj.onFail(function() {
                self.testStatus = false;
                if(self.onFail){
                    self.onFail();
                }
            });
            self.captchaObj.onRefresh(function() {
                // self.captchaObj.enable();
                // $(self.trigger).text(self.btnText);
            });
            self.captchaObj.onReady(function() {
                $(self.trigger).text(self.btnText);
            });
        }
    }

    this.geeTestInit = function() {
        var self = this;
        $(self.trigger).text('验证码加载中');
        $.ajax({
            // 获取id，challenge，success（是否启用failback）
            url: "/account/captcha?t=" + (new Date()).getTime(), // 加随机数防止缓存
            type: "get",
            dataType: "json",
            success: function(data) {
                // console.log(data)
                if (data.status) {
                    // 使用initGeetest接口
                    // 参数1：配置参数
                    // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
                    initGeetest({
                        gt: data.message.gt,
                        challenge: data.message.challenge,
                        product: "popup", // 产品形式，包括：float，embed，popup。注意只对PC版验证码有效
                        offline: !data.message.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
                    }, self.handlerEmbed.call(self));
                } else {
                    // console.log(data.errors);
                    $('#wait').text(data.errors.code);
                    toast(data.errors.code);
                    setTimeout(function() {
                        self.geeTestInit()
                    }, 5000);
                }
            }
        });
    }

    this.checkGeeTest = function() {
        var self = this;
        return self.testStatus;
    }

    this.getValidate = function() {
        var self = this;
        return self.captchaObj.getValidate();
    }

    this.popup = function(success, fail) {
        var self = this;
        $("#gee-trigger").click();
        self.onSuccess = success;
        self.onFail = fail;
    }

    this.refresh = function() {
        var self = this;
        // $(self.trigger).text('验证码加载中');
        self.testStatus = false;
        // self.captchaObj.disable();
        self.captchaObj.refresh();
    }
}
